package com.springbootsecuritydemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.springbootsecuritydemo.entity.LoginUser;
import com.springbootsecuritydemo.entity.UserEntity;
import com.springbootsecuritydemo.mapper.MenuMapper;
import com.springbootsecuritydemo.mapper.UserMapper;
import com.springbootsecuritydemo.service.UserQueryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 验证用户登录
 *
 * @author Daft_V
 * @date 2022/4/7 14:23
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    MenuMapper menuMapper;
    @Autowired
    UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询用户
        UserEntity userEntity = userMapper.queryUserList(username);
        //没有查询到用户就抛出异常
        if (Objects.isNull(userEntity)) {
            throw new RuntimeException("用户名或者密码错误");
        }
        //查询权限列表
        List<String> permissions = menuMapper.componentListByUserId(userEntity.getId());
        //把数据封装成UserDetails返回
        return new LoginUser(userEntity, permissions);
    }
}
